#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/19 19:49
# @Author  : Tom_zc
# @FileName: filter-event.py
# @Software: PyCharm
import os
import sys
import json
import logging
from pathlib import Path

CURR_DIR = Path(__file__).resolve()
ROOT_DIR = CURR_DIR.parent.parent.parent.parent
sys.path.append(ROOT_DIR.as_posix())

from scripts.utils.gitcode_helper import GitCodeHelper
from scripts.utils.parse_params import parse_repo_info_by_webhook_payload
from scripts.utils.common import func_retry

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


# filter the comment: /publish
class FilterPublishEventHelper:
    _comment = "/publish"

    def __init__(self, owner, repo, pr_number, token):
        self._git_helper = GitCodeHelper(owner, repo, pr_number, token)

    @func_retry()
    def check_publish(self):
        comments = self._git_helper.get_comment_by_pr_id()
        for comment in comments:
            if comment["body"].strip().startswith(self._comment):
                return True
        return False

    def create_comment(self, comment):
        self._git_helper.create_comment({"body": comment})


# filter the merge event
def main():
    payload = os.getenv("WEBHOOK_PAYLOAD")
    if not payload:
        logging.info("Error: Receive the empty WEBHOOK_PAYLOAD")
        sys.exit(-1)
    payload_body = json.loads(payload)
    event_type = payload_body.get("event_type")
    if not event_type:
        logging.info("Error:Receive the invalid request: event type: {}".format(event_type))
        sys.exit(-1)
    action = payload_body['object_attributes'].get("action")
    logging.info("-----------------------:{}".format(payload_body))
    logging.info("Receive the request: event type: {},action:{}"
                 .format(event_type, action))
    if event_type.lower() == "merge_request" and action == "merge":
        token = os.getenv("gitcode_token")
        if not token:
            logging.error("Error:env git_code_token must not be empty")
            sys.exit(-1)
        owner, repo, _, pr_number, _ = parse_repo_info_by_webhook_payload()
        filter_publish_event = FilterPublishEventHelper(owner, repo, pr_number, token)
        if filter_publish_event.check_publish():
            sys.exit(0)
        else:
            logging.error("Error: not receive the publish comment")
            sys.exit(-1)
    logging.error("Error: Receive the invalid request")
    sys.exit(-1)


if __name__ == '__main__':
    main()
